<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Administrator
 * Date: 12-9-19
 * Time: 下午4:14
 * To change this template use File | Settings | File Templates.
 */
require "constants.php";
class NEWS{
    private $db;
    private $table="news";
    private $per_page=3;
    private $offset;
    public $pager;
    function __construct($db){
        $this->db=$db;
    }
    function show($where=""){

        $this->pager=$this->_page($where);
        $sql="select * from ".$this->table." where 1=1 $where order by sort,add_time desc LIMIT ".$this->offset.",".$this->per_page;
        $result=$this->db->query_all($sql);
        return $result;
    }
    function add($id,$title,$catetree,$sort,$content){
        $sql="replace into ".$this->table." set id='$id',title='$title',`contents`='$content',cate='$catetree',
        sort='$sort',add_time='".time()."',operator='".$_SESSION['admininfo']['username']."'";
        $result=$this->db->query($sql);
        if($result){return true;}else{return false;}
    }
    function del($id){
        $sql="delete from ".$this->table." where id in($id)";

        $result=$this->db->query($sql);
        if($result){
            return true;
        }else{
            return false;
        }
    }
    function getNewsByid($id){//根据ID返回产品
        $sql="select * from ".$this->table." where id='$id'";
        $result=$this->db->query_all($sql);
        return $result[0];
    }
//////以下为私有方法

    private function _page($where){
        $data_count=$this->_getTotal($where);
        //分页
        $records_per_page = $this->per_page;
        $total_pages = ceil($data_count/$records_per_page);
        $pager = new pager(array('total'=>$data_count,'perpage'=>$records_per_page));
        $pagenum = intval($_GET['pagenum'])<1?1:intval($_GET['pagenum']);
        $pagenum = ($pagenum>$total_pages)?$total_pages:$pagenum;
        $pagenum = ($pagenum<1)?1:$pagenum;
        $this->offset = ($pagenum-1)*$records_per_page;
        return $pager;
    }
    private function _getTotal($where){
        //得到总数
        $data_count_req = $this->db->query_first("SELECT count(id) as t FROM ".$this->table." where 1=1 $where");
        $data_count = $data_count_req['t'];
        return $data_count;
    }
    private function _filter_result(&$result){//对结果集进行一些处理
        foreach($result as $key=>$value){
            if(is_array($value)){//如果是多为数组
                    $imgurl=pathinfo($value["img_url"]);
                    $result[$key]["img_th"]=$imgurl["dirname"]."/".$imgurl["filename"]."_th.".$imgurl["extension"];
                    $result[$key]["add_time"]=date("Y-m-d",$value["add_time"]);
            }else{
                if($key=="img_url"){
                    $imgurl=pathinfo($value["img_url"]);
                    $result["img_th"]=$imgurl["dirname"]."/".$imgurl["filename"]."_th.".$imgurl["extension"];
                }
            }
        }
    }
}